package com.mmall.admin.shiro;

import com.mmall.admin.pojo.entity.ResourceEntity;
import com.mmall.admin.pojo.result.UserPermissionResult;
import com.mmall.admin.service.AdminService;
import com.mmall.common.util.FilterOutUtil;
import com.mmall.common.base.ServerResponse;
import com.mmall.common.util.SpringUtil;
import jodd.util.StringPool;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.PermissionsAuthorizationFilter;
import org.apache.shiro.web.util.WebUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Set;

/**
 * 权限校验 filter
 *
 * @author gg
 * @version PermsFilter.java, v 0.1 2019-04-30 13:29 gg
 */
public class PermsFilter extends PermissionsAuthorizationFilter {

    /**
     * 跨域处理
     *
     * @param request     ServletRequest
     * @param response    ServletResponse
     * @param mappedValue Object
     * @return boolean
     * @throws Exception Exception
     */
    @Override
    public boolean onPreHandle(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        ShiroBaseFilter shiroBaseFilter = new ShiroBaseFilter();
        boolean result = shiroBaseFilter.preHandle(request, response);
        if (result) {
            return true;
        } else {
            return super.onPreHandle(request, response, mappedValue);
        }
    }

    /**
     * 权限校验核心逻辑
     *
     * @param request     ServletRequest
     * @param response    ServletResponse
     * @param mappedValue Object
     * @return boolean
     * @throws IOException IOException
     */
    @Override
    public boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws IOException {
        boolean isPermitted = false;
        ShiroUser shiroUser = ShiroBaseFilter.getShiroUser(request);
        if(shiroUser == null){
            return false;
        }
        ShiroOperation.THREAD_LOCAL.set(shiroUser);
        HttpServletRequest req = (HttpServletRequest) request;
        Boolean checkShopId = ShiroBaseFilter.checkShopId(req, shiroUser,response);
        if (!checkShopId) {
            return checkShopId;
        }
        AdminService adminService = SpringUtil.getBean(AdminService.class);
        UserPermissionResult userPermissionResult = adminService.getPermissionByUserName(shiroUser.getUsername());
        Set<ResourceEntity> resourceEntitySet = userPermissionResult.getResourceEntitySet();
        String requestUrl = req.getRequestURL().toString();
        for (ResourceEntity resourceEntity : resourceEntitySet) {
            String url = resourceEntity.getCode().replace(StringPool.UNDERSCORE, StringPool.SLASH);
            boolean contains = requestUrl.contains(url);
            if (contains) {
                isPermitted = true;
            }
        }

        return isPermitted;
    }

    /**
     * 权限校验失败后的处理方法，通过重写该方法取消原有的重定向
     *
     * @param request  ServletRequest
     * @param response ServletResponse
     * @return boolean
     * @throws IOException IOException
     */
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws IOException {
        HttpServletResponse res = (HttpServletResponse) response;
        Subject subject = getSubject(request, response);
        if (subject.getPrincipal() == null) {
            ServerResponse error = ServerResponse.createByErrorCodeMessage(403, "请先进行登录");
            FilterOutUtil.out(error, response);
        } else {
            String errorStr = res.getHeader("Error");
            if (StringUtils.isNoneBlank(errorStr)) {
                res.setContentType("application/json;charset=utf-8");
                PrintWriter out = null;
                out = res.getWriter();
                out.write(errorStr);
                out.flush();
            }else {
                ServerResponse error = ServerResponse.createByErrorCodeMessage(1, "无权限，请联系管理员");
                FilterOutUtil.out(error, response);
            }
        }
        return false;
    }


}